package com.LeeCode;

/**
 * 合并两个有序链表
 */

public class Code021 {
    public static void main(String[] args) {
        int[] arr1 = {1, 2, 4};
        int[] arr2 = {3, 4, 5};
        ListNode list1 = Utils.arrayToListNode(arr1);
        ListNode list2 = Utils.arrayToListNode(arr2);
        Utils.printListNode(new Code021().mergeTwoLists(list1, list2));
    }

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode head = new ListNode(0);
        ListNode cur = head;

        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                cur.next = list1;
                cur = cur.next;
                list1 = list1.next;
            } else {
                cur.next = list2;
                cur = cur.next;
                list2 = list2.next;
            }
        }
        if (list1 != null) {
            cur.next = list1;
        }
        if (list2 != null) {
            cur.next = list2;
        }
        return head.next;
    }
}
